﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Smartdispatch
{
    static class Program
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);

        /// <summary>
        ///  创建指定窗口的线程设置到前台，并且激活该窗口。键盘输入转向该窗口，并为用户改变各种可视的记号。
        ///  系统给创建前台窗口的线程分配的权限稍高于其他线程。 
        /// </summary>
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param>
        /// <returns>如果窗口设入了前台，返回值为非零；如果窗口未被设入前台，返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        // 指示窗口为普通显示
        private const int WS_SHOWNORMAL = 1;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process process = RunningInstance();
            if (process == null)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new WaterSmart());
            }
            else
            {
                HandleRunningInstance(process);
            }
        }
        private static Process RunningInstance()
        {
            // 获取当前活动的进程
            Process currentProcess = Process.GetCurrentProcess();

            // 根据当前进程的进程名获得进程集合
            // 如果该程序运行，进程的数量大于1
            Process[] processcollection = Process.GetProcessesByName(currentProcess.ProcessName.Replace(".vshost", ""));
            foreach (Process process in processcollection)
            {
                // 如果进程ID不等于当前运行进程的ID以及运行进程的文件路径等于当前进程的文件路径
                // 则说明同一个该程序已经运行了，此时将返回已经运行的进程
                if (process.Id != currentProcess.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == process.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// 显示已运行的程序
        /// </summary>
        /// <param name="instance"></param>
        private static void HandleRunningInstance(Process instance)
        {
            // 显示窗口
            ShowWindow(instance.MainWindowHandle, WS_SHOWNORMAL);

            // 把窗体放在前端
            SetForegroundWindow(instance.MainWindowHandle);
        }
    }
}
